package czu.caohao.socket;

import java.io.*;
import java.net.Socket;
import java.sql.*;

public class SocketUtils {

    public static Socket connectServerTCP(String host, Integer port) {
        Socket socket = null;
        try {
            socket = new Socket(host, port);
        } catch (Exception e) {
            System.out.println("客户端连接异常");
            e.printStackTrace();
        }
        return socket;
    }

    public static boolean closeSocket(Socket socket) {
        if (socket != null) {
            try {
                socket.close();
                return true;
            } catch (IOException e) {
                e.printStackTrace();
                return false;
            }
        }
        return true;
    }

    public static String sendMessage(Socket socket, String msg) {
        if (socket != null || msg != null) {
            try {
                // 向服务端发送信息
                BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
                writer.write(msg);
                writer.flush();

                // 接受从服务端发送过来的响应
                BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                StringBuffer sb = new StringBuffer();
                reader.lines().map((s) -> sb.append(s));

                return sb.toString();
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
        } else {
            return null;
        }
    }

    public static void main(String[] args) {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            String URL = "jdbc:mysql://192.168.43.13:13307/mysql?serverTimezone=GMT%2B8";
            String USER = "root";
            String PASSWORD = "root";
            Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);
            Statement st = conn.createStatement();
            ResultSet rs = st.executeQuery("show master status");
            for (int i = 1; i < rs.getMetaData().getColumnCount() + 1; i++) {
                //System.out.println("column_name:"+rs.getMetaData().getColumnName(i)+" "+"column_label:"+rs.getMetaData().getColumnLabel(i));
                System.out.println(rs.getMetaData().getColumnName(i));
            }
            //while(rs.next()){
            //    System.out.println(rs.getString("Slave_IO_State")+" "
            //        +rs.getString("Master_Host"));
            //}
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
